import router from '@/router'
import store from './store'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRouter } from '@/router'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      if (!store.getters.userId) {
        const { roles: { menus }} = await store.dispatch('user/getUserInfoAction')
        const addRouter = asyncRouter.filter(item => {
          return menus.includes(item.name)
        })
        store.commit('user/addRoutes', addRouter)
        router.addRoutes([...addRouter, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    next()
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }
  }
})

router.afterEach(() => {
  nprogress.done()
})
